package com.start.code.generator.controller;

import com.start.code.generator.service.StartCodeGeneratorService;
import com.start.code.generator.vo.StartCreateCodeVo;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("start/code/generator")
public class CodeGeneratorController {
    @Autowired
    private StartCodeGeneratorService startCodeGeneratorService;


    @PostMapping("/createCode/{dataSourcesKey}")
    public void createCode(HttpServletResponse response, @PathVariable("dataSourcesKey") String dataSourcesKey, @RequestBody StartCreateCodeVo codeVo) {
        byte[] bytes = startCodeGeneratorService.generatorCode(dataSourcesKey, codeVo);
        response.reset();
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", codeVo.getTableName()));
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(bytes.length));
        response.setContentType("application/octet-stream; charset=UTF-8");
        try {
            IOUtils.write(bytes, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
